<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设置背景图片并本地存储</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f0f0;
        }
        .upload-container {
            text-align: center;
        }
        .preview {
            width: 300px;
            height: 200px;
            margin-top: 20px;
            background-size: cover;
            background-position: center;
        }
    </style>
</head>
<body>
<div class="upload-container">
    <input type="file" id="imageUpload" accept="image/*">
    <div class="preview"></div>
</div>

<script>
    document.getElementById('imageUpload').addEventListener('change', function(event) {
        const file = event.target.files[0]; // 获取用户选择的文件

        if (file) {
            const reader = new FileReader(); // 创建FileReader对象

            // 当文件读取完成时触发
            reader.onload = function(e) {
                const imageUrl = e.target.result; // 获取图片的base64编码
                document.querySelector('.preview').style.backgroundImage = `url(${imageUrl})`;

                // 将图片数据存储到 localStorage
                localStorage.setItem('background', imageUrl);
            };

            // 开始读取文件内容为Data URL
            reader.readAsDataURL(file);
        } else {
            alert('请选择一张图片！');
        }
    });

    // 页面加载时，从 localStorage 恢复背景图片
    window.onload = function() {
        const savedImage = localStorage.getItem('backgroundImage');
        if (savedImage) {
            document.querySelector('.preview').style.backgroundImage = `url(${savedImage})`;
        }
    };
</script>
</body>
</html>
